package com.uniledger.exchange.login.fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.uniledger.commonlib.util.ToastUtils;
import com.uniledger.commonlib.view.CountDownButton;
import com.uniledger.exchange.R;
import com.uniledger.exchange.login.Admin;
import com.uniledger.exchange.model.HttpResult;
import com.uniledger.exchange.model.OkSingleton;
import com.uniledger.exchange.model.StellarAsset;
import com.uniledger.exchange.model.api.Api;
import com.uniledger.exchange.model.rx.RxException;
import com.uniledger.exchange.model.rx.RxSchedulers;
import com.uniledger.exchange.wallet.WalletKey;

import org.stellar.sdk.KeyPair;

import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.novacrypto.bip39.MnemonicGenerator;
import io.github.novacrypto.bip39.SeedCalculator;
import io.github.novacrypto.bip39.Words;
import io.github.novacrypto.bip39.wordlists.English;
import io.reactivex.functions.Consumer;

/**
 * https://github.com/sfyc23/CountDownList
 * 验证码
 */

public class SignUpThreeFragment extends SignUpFragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private Admin admin;
    private String mParam2;

    @BindView(R.id.btn_send_sms)
    CountDownButton countDownButton;

    @BindView(R.id.et_code)
    EditText code;

    @OnClick(R.id.btn_send_sms)
    void countDown() {
        countDownButton.start();
    }

    public SignUpThreeFragment() {
        // Required empty public constructor
    }

    public static SignUpThreeFragment newInstance(Admin param1, String param2) {
        SignUpThreeFragment fragment = new SignUpThreeFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            admin = getArguments().getParcelable(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_sign_up_three, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        countDownButton.setOnCountDownFinishListener(new CountDownButton.OnCountDownFinishListener() {
            @Override
            public void onFinish() {
                //TODO 倒计时结束
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        countDownButton.start();
    }

    @Override
    public void onStop() {
        super.onStop();
        countDownButton.stop();
    }

    @Override
    public void onClick(View v) {
        //TODO 提交注册信息
        String codeStr = code.getText().toString().trim();
        if (TextUtils.isEmpty(codeStr)) {

        } else {
            //开始注册
            upListener.dialog().show();
            countDownButton.stop();
            new AccountTask(codeStr).execute();
        }
    }

    /**
     * 生成账户
     */
    class AccountTask extends AsyncTask<String, Integer, WalletKey> {

        private String codeStr;

        public AccountTask(String codeStr) {
            this.codeStr = codeStr;
        }

        private String generateNewMnemonic(Words wordCount) {
            StringBuilder sb = new StringBuilder();
            byte[] entropy = new byte[wordCount.byteLength()];
            new SecureRandom().nextBytes(entropy);
            new MnemonicGenerator(English.INSTANCE)
                    .createMnemonic(entropy, sb::append);
            return sb.toString();
        }

        @Override
        protected WalletKey doInBackground(String... strings) {

            String mnemonic = generateNewMnemonic(Words.TWELVE);

            //助记词+口令
            final byte[] seed = new SeedCalculator().calculateSeed(mnemonic, "");
            KeyPair keyPair = KeyPair.fromSecretSeed(seed);

            //保存私钥
            OkSingleton.getInstance().setSourceKeyPair(keyPair);

            return new WalletKey(admin.firstName, mnemonic, keyPair.getAccountId());
        }

        @Override
        protected void onPostExecute(WalletKey walletKey) {
            super.onPostExecute(walletKey);
            Map<String, String> map = new HashMap<>();
            map.put("name", admin.firstName + admin.lastName);
            map.put("country_code", admin.countryCode);
            map.put("mobile", admin.mobile);
            map.put("captcha", codeStr);
            map.put("stellar_addr", walletKey.accountId);//TODO 需要生成

            Api.getService().signUp(map)
                    .compose(RxSchedulers.io_main())
                    .subscribe(new Consumer<HttpResult<StellarAsset>>() {
                        @Override
                        public void accept(HttpResult<StellarAsset> httpResult) throws Exception {
                            if (httpResult.code == 0) {
                                //TODO 密钥数据存入数据库
                                walletKey.uid = 123;
                                admin.token = httpResult.data.token;
                                admin.expire = httpResult.data.expired;
                                admin.avatar = httpResult.data.logo;
                                admin.baseAccountId = httpResult.data.base_addr;
                                admin.issuingAccountId = httpResult.data.issue_addr;
                                admin.uid = 123;
                                admin.walletFlag = 2;
                                admin.isSignIn = true;
                                admin.walletKey = walletKey;
                                upListener.success(admin);
                            } else {
                                ToastUtils.show(httpResult.msg);
                            }
                        }
                    }, new RxException<>(new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {

                        }
                    }));
        }
    }


}
